import {createSlice} from "@reduxjs/toolkit";

//创建购物车模块
const cartSlice = createSlice({
    name:'cart',
    initialState:{
        cartList:localStorage.getItem('cartList')? JSON.parse(localStorage.getItem('cartList')):[],
    },
    reducers:{
    //    添加购物车
        addCart(state,{type,payload}){
            const index = state.cartList.findIndex(v=>v.id===payload.id)
            if(index>-1){
                state.cartList[index].buyNum+=1
            }else{
                state.cartList.unshift({
                    id:Math.random().toString(36).slice(2),
                    ...payload,
                    buyNum:1
                })
            }
            localStorage.setItem('cartList',JSON.stringify(state.cartList))
        },
    //    修改购车数量
        changeNum(state,{type,payload}){
            const index= state.cartList.findIndex(v=>v.id===payload.id)
            if(payload.num===1||payload.num===-1){
                state.cartList[index].buyNum+=payload.num
            }else{
                state.cartList[index].buyNum = payload.num
            }

            if(state.cartList[index].buyNum<=0){
                state.cartList.splice(index,1)
            }
            localStorage.setItem('cartList',JSON.stringify(state.cartList))
        }
    }
})
const cart = cartSlice.reducer
export const {addCart,changeNum} = cartSlice.actions
export default cart